package com.atguigu.tingshu.album.receiver;

import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.concurrent.TimeUnit;

/**
 * ClassName: AlbumReceiver
 * Package: com.atguigu.tingshu.album.receiver
 * Description:
 *
 * @Author 咚咚小圆帽
 * @Create 2025/7/27 Sunday 14:38
 * @Version 1.0
 */
@Component
@Slf4j
public class AlbumReceiver {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TrackInfoService trackInfoService;

    /**
     * 监听到更新声音统计消息，更新数据库中声音表跟专辑表的统计信息。
     *
     * @param trackStatMqVo
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK, durable = "true"),
            key = {MqConst.ROUTING_TRACK_STAT_UPDATE}
    ))
    public void updateTrackStat(TrackStatMqVo trackStatMqVo, Message message, Channel channel) {
        if (trackStatMqVo != null) {
            log.info("监听到更新声音统计消息，trackStatMqVo：{}", trackStatMqVo);
            //1.消费者幂等性处理，避免同一个统计MQ消息被消费者多次消费，采用Rediss的set ex nx命令来实现。
            String key = RedisConstant.BUSINESS_PREFIX + "db:" + trackStatMqVo.getBusinessNo();
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "", 10, TimeUnit.MINUTES);

            if (flag) {

                try {
                    //2.调用业务逻辑层更新声音以及专辑统计信息。
                    trackInfoService.updateTrackStat(trackStatMqVo);
                } catch (Exception e) {
                    //业务发生异常时，将幂等性缓存key删除
                    redisTemplate.delete(key);
                    //确认消息发送失败，将消息再次入队，发送确认消息
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                    return;
                }

            }


        }

    }

}
